﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace uzing
{
    public enum UZING_TCP
    {
        BLOCKING,
        NON_BLOCKING
    }

    public class CTcpClientSync
    {
        TcpClient client;
        byte[] DataBuffer;

        public string errorMessage;

        public CTcpClientSync(int BufferSize)
        {
            client = null;
            DataBuffer = new byte[BufferSize];
        }

        public void RegisterClient(TcpClient Client)
        {
            client = Client;
        }

        public void ConnectToServer(string IpAddress, int Port)
        {
            client = new TcpClient();
            client.Connect(IpAddress, Port);
        }

        public int SendData(byte[] Data, int Offset, int Size)
        {
            if (null != client)
            {
                try
                {
                    client.GetStream().Write(Data, Offset, Size);
                }
                catch (IOException e)
                {
                    client = null;
                    e.ToString();
                }
                return Size;
            }
            return 0;
        }

        public void Receive(byte[] Data, int Offset, int Size)
        {
            var sock = client.Client;
            var stream = client.GetStream();

            while (stream.CanRead && Size != 0)
            {
                int available = sock.Available;
                if (available >= Size)
                {
                    stream.Read(Data, Offset, Size);
                    Size = 0;
                }
                else
                {
                    stream.Read(Data, Offset, available);
                    Offset += available;
                    Size -= available;
                }
            }
        }
    }
}
